import { useEffect } from "react";
import { useReducer } from "react";
import { ActionType, ReducerAction, StateType } from "../searchPropsContext";

const updateTabsConfig = (state: StateType, action: ReducerAction[ActionType.UPDATE_TABS_CONFIG]) => {
    const nextTabs = action.payload.slice();
    const newTabsCOnfig = state.tabsConfig.map((item) => {
        const index = action.payload.findIndex((tab) => tab.guid === item.guid);
        if (index !== -1) {
            const nextTag = nextTabs[index];
            nextTabs.splice(index, 1);
            return nextTag;
        }
        return item;
    });
    return {
        ...state,
        tagConfig: [...newTabsCOnfig, ...nextTabs],
    };
}

const reducer = (state: StateType, action: ReducerAction[ActionType]): StateType => {
    switch (action.type) {
        case ActionType.UPDATE_KEYWORDS_SWITCH:
            return {
                ...state,
                hotKeywordsSwitch: action.payload,
            };
        case ActionType.UPDATE_KEYWORDS_POSITION:
            return {
                ...state,
                hotKeywordsPosition: action.payload,
            };
        case ActionType.UPDATE_KEYWORDS_NUMBER:
            return {
                ...state,
                hotKeywordsNumber: action.payload,
            };
        case ActionType.UPDATE_TABS_CONFIG:
            return updateTabsConfig(state, action);
        case ActionType.UPDATE_REFRESH:
            return {
                ...state,
                ...action.payload
            }
        default:
            return state;
    }
}

export const useStateReducer = (props: StateType) => {
    const [state, dispatch] = useReducer(reducer, props);

    useEffect(() => {
        dispatch({
            type: ActionType.UPDATE_REFRESH,
            payload: props,
        });
    }, [props]);

    return { state, dispatch };
}